package cn.com.yusys.yusp.message.service.message.filter.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import org.springframework.stereotype.Service;

import cn.com.yusys.yusp.message.service.message.filter.EmailAttachmentCustomInterface;
@Service
public class EmailAttachmentCustomTest implements EmailAttachmentCustomInterface{

	@Override
	public Map<String, byte[]> getAttachments(String messageType, String userNo) {
		Map<String, byte[]> attach = new HashMap<String, byte[]>();
		try {
			//File folder = new File("C:\\Users\\figue\\Desktop\\admin-bug");
			ClassLoader classLoader = getClass().getClassLoader();
			URL url = classLoader.getResource("cert");
			File folder = new File(url.getFile());
			if(null!=folder&&folder.exists()&&folder.isDirectory()){
				File[] files = folder.listFiles();
				for(File fileT: files){
					if(fileT.isFile()&&fileT.exists()){
						String fileName = fileT.getName();
						FileInputStream fileInputStream = null;
						//modify by Cytus_ at 20180904 修改sonar扫描出现的bug， 此处使用try-catch-finally关闭流对象
						try {
						    fileInputStream = new FileInputStream(fileT);
						    byte[] buff = fileToByte(fileInputStream, fileT.length());
	                        attach.put(fileName, buff);
	                        System.out.println("Email attachment name>>>"+fileName);
						} catch (IOException e) {
						    
						} finally {
						    try {
    						    if (Objects.nonNull(fileInputStream))
    						        fileInputStream.close();
						    } catch (IOException e) {
						        
						    }
						}
					}
				}
			}
		
		} catch (Exception e) {
			e.printStackTrace();
		}
		return attach;
	}

	@Override
	public boolean isFixed(String messageType) {
		if(messageType.equals("dyxxcs")){
			return true;
		}
		return false;
	}

	private byte[] fileToByte(InputStream inStream, long fileLength) throws IOException {

		byte[] buffer = new byte[256 * 1024];
		byte[] fileBuffer = new byte[(int) fileLength];

		int count = 0;
		int length = 0;

		while ((length = inStream.read(buffer)) != -1) {
			for (int i = 0; i < length; ++i) {
				fileBuffer[count + i] = buffer[i];
			}
			count += length;
		}
		return fileBuffer;
	}

}
